<script setup>
import {reactive, ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
const formRef = ref()

const validateOne = (rule, value, callback) => {
  if (value !== data.user.password) {
    callback(new Error("原密码错误!"))
  } else {
    callback()
  }
}
const validateTwo = (rule, value, callback) => {
  if (value !== data.form.newpassword) {
    callback(new Error("密码不一致!"))
  } else {
    callback()
  }
}
const data=reactive({
  form:{},
  rules: {
    orgpassword: [
      {required: true, message: "请输入原始密码", trigger: "blur"},
      {min: 3, message: "最少3位数", trigger: "blur"},
      {validator: validateOne, trigger: "blur"},
    ],
    newpassword: [
      {required: true, message: "请输入新密码", trigger: "blur"},
      {min: 3, message: "最少3位数", trigger: "blur"},

    ],
    confirmpassword: [
      {required: true, message: "请再次输入密码", trigger: "blur"},
      {min: 3, message: "最少3位数", trigger: "blur"},
      {validator: validateTwo, trigger: "blur"},
    ],
  },
  user:JSON.parse(localStorage.getItem('code_user') || '{}'),
})
const updatePassword = (res) => {
  formRef.value.validate(valid => {
    if (valid) {
      data.user.password = data.form.newpassword
      request.post('/updatePassword',data.user).then(res => {
        if(res.code === 200) {
          localStorage.removeItem('code_user');
          ElMessage.success("密码修改成功")
          router.push('/login');
        }
      })
    }
  })
}
</script>

<template>

  <div style="width: 50%;background-color: #b8b8b8">
    <div style="font-size: 15px">
      修改密码
    </div>
    <el-form label-width="80px"
             :rules="data.rules"
             :model="data.form"
             ref="formRef"
             style="padding: 20px 30px 0 0">
      <el-form-item prop="orgpassword" label="原密码">
        <el-input show-password v-model="data.form.orgpassword" autocomplete="off" placeholder="请输入原密码"/>
      </el-form-item>
      <el-form-item prop="newpassword" label="新密码">
        <el-input v-model="data.form.newpassword" autocomplete="off" placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item prop="confirmpassword" label="确认密码">
        <el-input v-model="data.form.confirmpassword" autocomplete="off" placeholder="请再次输入密码"/>
      </el-form-item>

    </el-form>
    <div style="text-align: center">
      <el-button @click="updatePassword" type="success" size="large" style="margin: 20px 50px;width: 80px">
        确定
      </el-button>
    </div>
  </div>
</template>

<style scoped>

</style>
